package com.wanmait.wisdom.manage.controller;


import com.github.pagehelper.PageInfo;
import com.wanmait.wisdom.entity.Bulletin;
import com.wanmait.wisdom.manage.service.ManageBulletinService;
import com.wanmait.wisdom.util.AjaxResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("manage")
public class ManageBulletinController {
    @Resource
    private ManageBulletinService manageBulletinService;

    @PostMapping("addBulletin")
    public AjaxResult addBulletin(@RequestBody Bulletin bulletin){
        manageBulletinService.addBulletin(bulletin);
        return AjaxResult.success("添加成功");
    }

    @GetMapping("findAllBulletin")
    public AjaxResult findAllBulletin(String title,Integer pageNum, Date startTime, Date endTime){
        if (pageNum == null || pageNum < 1){
            pageNum=1;
        }

        PageInfo<Bulletin> pageInfo = manageBulletinService.findAllBulletin(title,pageNum,startTime,endTime,10);
        if (pageInfo.getList()==null){
            return AjaxResult.error(9999,"查询失败");
        }
        return AjaxResult.success("查询成功").put("pageInfo",pageInfo);
    }

    @PostMapping("bulletinUploadImg")
    public AjaxResult bulletinUploadImg(MultipartFile file){
        try {
            String path= ResourceUtils.getURL("classpath:").getPath()+"/static/bulletinPic";
            String fileName = UUID.randomUUID().toString() .replaceAll("-","")+"."+ FilenameUtils.getExtension(file.getOriginalFilename());
            file.transferTo(new File(path,fileName));
            return AjaxResult.success("上传成功").put("fileName",fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.error("上传失败");
    }

}
